<template>
	
</template>

<script setup>
	import { ref, reactive, nextTick } from 'vue'
	import { onShow, onLoad } from '@dcloudio/uni-app'
	import appConfig from '@/config/appConfig.js'
	import storageManage from '@/util/storageManage.js'
	import { $fansLogin, $scoreRecordSave, $placeOpenid, $confirmInvite, $apiDelFanUser } from '@/http/apiManager.js'
	import { reLaunch, navigateTo } from '@/util/interceptors.js'
	import $infoBox from '@/common/fun.js'
	import dayjs from 'dayjs'

	/**引流类型 sence 中获取4、6 其余的在options中
	 * 0自然流量

     1转发朋友/群 ，对应字段有：
     activity_id, inviter_id (存储为fans_id)

     2公众号渠道码 ，对应字段有：
     inviter_id (存储为activity_channel_id)

     3广告，对应字段有：
     activity_id (微信WeChat，抖音TikTok)
	 
	 4扫码领券 ，对应字段有：
     activityId, inviter_id (存储为qrcode_record_id)

     5分享到朋友圈 ，对应字段有：
     activity_id, inviter_id (用户fans_id)
	 
	 6小程序码
	 activity_id, inviter_id(存储为fans_id)
	 
	 redirect_uri	重定向页面
	 */
	onLoad((options) => {
		
		// 小程序码类型--------------------------------------------
		if (options.scene) {
			/**
			 * scene
			 * 1 activityId id 扫码领券(id为qrcodeRecordId小程序码id)
			 * 2 activityId acteType 扫码派券引导用户授权
			 * 3 inviterId inviterType === 6 福分乐园邀请好友（inviterId为邀请人fansId）
			 */
			const sceneObject = getQueryParams(decodeURIComponent(options.scene))
			const { activityId, id, inviterId, inviterType, acteType } = sceneObject
			if (inviterId && inviterType == 6) { // 福分乐园邀请好友 inviterId为邀请人fansId
				// 记录扫码时间 用于判断用户扫码时间是否早于注册时间 用来给后端判断用户是否是新客
				getApp().globalData.temp_sacn_time = dayjs().format('YYYY-MM-DD HH:mm:ss')
				getApp().globalData.temp_score_scene = sceneObject
				getApp().globalData.inviterType = 6
			} else if (activityId && id) { // 扫码领券
				getApp().globalData.temp_scan_scene = sceneObject
				getApp().globalData.inviterType = 4
			} else if (activityId && acteType === 'issue') { // 扫码派券引导用户授权
				getApp().globalData.temp_issueid = activityId
			}
			getApp().globalData.inviterInfo = JSON.stringify(sceneObject) // 把小程序码原始数据回传给后端 登录时需要使用该字段 用于存储当前新用户来源
			return
		}
		// 转发类型--------------------------------------------
		// 分享标识符：share share中携带活动id和分享人userId
		if (options.share) { // 越减越便宜拉新好友/群 包括其他活动分享也走这里
			// 存储临时变量
			getApp().globalData.temp_share = options.share
			getApp().globalData.temp_share_invited_json = options.invitedJson // 动态页面参数（传递受邀页面的动态参数 配置的页面样式）
			getApp().globalData.inviterInfo = options.share
			getApp().globalData.inviterType = 1
		}
		// 其他类型--------------------------------------------
		// 网页渠道码标识符：eventKey
		// options.eventKey = JSON.stringify({"date":"2024-12-04","activityId":1,"activityNum":2,"openId":storageManage.placeOpenId(),"channelId":1,channelCode:"M1700111832",channelType:1})
		if (options.eventKey) { // 从海报扫码而来
			// 存储临时变量
			getApp().globalData.temp_eventkey = options.eventKey
			getApp().globalData.inviterInfo = options.eventKey
			getApp().globalData.inviterType = 2
		}
		// 重定向页面
		// options.redirect_uri = '/pageUser/scoreHistory/index'
		if (options.redirect_uri) { // 页面重定向 公共号
			getApp().globalData.temp_redirect_uri = decodeURIComponent(options.redirect_uri)
		}
	})

	onShow(() => {
		getPayOpenId()
	})

	/**
	 * 获取公众号openid
	 */
	async function getPayOpenId() {
		const payOpenId = storageManage.payOpenId()
		const fansId = storageManage.fansId()
		if (payOpenId && fansId) {
			login()
		} else {
			// 获取payOpenId
			uni.reLaunch({
				url: `/pages/openid/openid`
			})
		}
	}

	function login() {
		// 已经登录并且 不再走登录 跳转该跳的页面
		if (storageManage.token() && storageManage.liteOpenId()) {
			intoContentPage()
			return
		}
		uni.login({
			success(res) {
				let uploadObject = {
					wxcode: res.code,
					// appId: appConfig.appId,
					fansId: storageManage.fansId(),
					// officialAppId: appConfig.officialAppId,
					payOpenId: storageManage.payOpenId(),
					inviterType: 0, // 默认自然流量
				}
				if (getApp().globalData.inviterInfo && getApp().globalData.inviterType) {
					uploadObject.inviterInfo = getApp().globalData.inviterInfo
					uploadObject.inviterType = getApp().globalData.inviterType
					// 删除临时变量
					delete getApp().globalData.inviterInfo
					delete getApp().globalData.inviterType
				}
				$fansLogin(uploadObject).then(({ bizData }) => {
					const { token, userId, isLogin, isBind, placeOpenId, authGzhUrl, placeAppid, openId: liteOpenId, dataKey, state, logoutTime } = bizData
					if (!token) {
						$infoBox.toast("登录失败")
						return
					}
					storageManage.token(token)
					if (state == 1) {
						let logoutTimeCopy = logoutTime?.slice(0, 10);
						uni.showModal({
							title: '提示',
							content: `您的账户正在注销中，预计${logoutTimeCopy}完成注销，是否要恢复使用`,
							showCancel: false,
							confirmText: "恢复",
							success: function(res) {
								if (res.confirm) {
									$apiDelFanUser({
										state: 0
									}).then((res) => {
										if (res.code == 0) {
											uni.reLaunch({
												url: '/pages/welcome/index'
											})
										}
									})
								}
							}
						});
					} else if (state == 2) {
						uni.showModal({
							title: '提示',
							content: `您的账户已经注销，无法登录本小程序`,
							showCancel: false,
							confirmText: "确定",
							success: function(res) {}
						});
					} else {
						if (dataKey) { // 兼容老后台 下一版本可删除该dataKey的赋值
							storageManage.dataKey(dataKey)
						}
						storageManage.userId(userId)
						storageManage.isLogin(!!isLogin)
						storageManage.isBind(!!isBind)
						storageManage.liteOpenId(liteOpenId) // 用户小程序openId
						if (appConfig.appId !== 'wx554f86dfa21d0373'){	// 针对郑邮享
							intoContentPage()
							return
						}
						if (placeOpenId) {
							storageManage.placeOpenId('wx2a7a68d3bcb2ef2c',placeOpenId)
							intoContentPage()
						} else {
							getApp().globalData.temp_path = '/pages/welcome/index'
							getApp().globalData.temp_official_appid = 'wx2a7a68d3bcb2ef2c'
							appConfig.url = 'https://zyx.post183.net/zyxfans/official/openid/openid_code.html'
							uni.reLaunch({
								url: `/pages/openid/openid`
							})
						}
					}


				})
			},
			fail() {
				$infoBox.toast("登录失败")
			}
		})
	}

	/**
	 * 进入具体页面
	 */
	function intoContentPage() {
		// 海报
		const eventKey = getApp().globalData.temp_eventkey
		if (eventKey) {
			// const { activityId, activityTemplateNo, channelId } = JSON.parse(eventKey.trim())
			const { activityId, activityNum, channelCode, channelType, channelId, openId, date } = JSON.parse(eventKey.trim())
			if (typeof(activityNum) == "number" && activityNum > 1 && channelCode && channelType) {
				let targetUrl = `/pageUser/mchActivityCode/mchActivityCode?channelCode=${channelCode}&channelType=${channelType}&date=${date}&activityChannelId=${channelId}`
				// if (openId !== storageManage.placeOpenId()) { // 展示副路由页面
				// 	targetUrl += `&from=${1}`
				// }
				// 商户活动列表
				uni.reLaunch({
					url: targetUrl,
					success() {
						// 清除临时变量
						delete getApp().globalData.temp_eventkey
					}
				})
			} else if (typeof(activityNum) == "number" && activityNum == 1 && activityId) {
				// 活动详情页
				let targetUrl = `?activityId=${activityId}&date=${date}&activityChannelId=${channelId}`
				// if (openId !== storageManage.placeOpenId()) { // 展示副路由页面
				// 	targetUrl += `&from=${1}`
				// }
				reLaunch({
					url: targetUrl,
					success() {
						// 清除临时变量
						delete getApp().globalData.temp_eventkey
					}
				})
			} else {
				$infoBox.toast('该商户未开展任何活动', { duration: 2000 })
				setTimeout(() => {
					// 首页
					uni.switchTab({
						url: '/pages/index/index',
						success() {
							// 清除临时变量
							delete getApp().globalData.temp_eventkey
						}
					});
				}, 2000)
			}
			return
		}
		// 扫码领券活动
		const scanScene = getApp().globalData.temp_scan_scene
		if (scanScene) {
			// 解析参数中的活动id
			const { activityId } = scanScene
			reLaunch({
				url: `?activityId=${activityId}&scene=${JSON.stringify(scanScene)}`,
				success() {
					// 清除临时变量
					delete getApp().globalData.temp_scan_scene
				}
			})
			return
		}
		// 扫码派券引导用户授权
		const issueId = getApp().globalData.temp_issueid
		if (issueId) {
			reLaunch({
				url: `?activityId=${issueId}`,
				success() {
					// 清除临时变量
					delete getApp().globalData.temp_issueid
				}
			})
			return
		}
		// 福分拉新
		const scoreScene = getApp().globalData.temp_score_scene
		const time = getApp().globalData.temp_sacn_time // 用户扫码时间
		if (scoreScene) {
			// 解析参数中的活动id
			const { inviterId } = scoreScene
			// 发起拉新请求
			$confirmInvite({ inviterId, time }).then(({ code }) => {
				if (code === 0) {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
			}).catch((err) => {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 2000)
			}).finally(() => {
				// 清除临时变量
				delete getApp().globalData.temp_score_scene
				delete getApp().globalData.temp_sacn_time
			})
			return
		}
		// 越减越便宜 拉新分享好友/朋友圈 包括其他活动的分享
		const share = getApp().globalData.temp_share
		const invitedJson = getApp().globalData.temp_share_invited_json
		if (share) {
			const { activityId, url } = JSON.parse(share)
			// 判断是否指定跳转页面
			if (url) {
				uni.reLaunch({
					url: `${url}?shareParams=${share}&invitedJson=${invitedJson}`,
					success() {
						// 清除临时变量
						delete getApp().globalData.temp_share
						delete getApp().globalData.temp_share_invited_json
					}
				})
			} else { // 没有指定页面 跳转活动详情页
				reLaunch({
					url: `?activityId=${activityId}&shareParams=${share}&invitedJson=${invitedJson}`,
					success() {
						// 清除临时变量
						delete getApp().globalData.temp_share
						delete getApp().globalData.temp_share_invited_json
					}
				})
			}
			return
		}
		// 页面重定向
		const redirect_uri = getApp().globalData.temp_redirect_uri
		const redirect_uri_type = getApp().globalData.temp_redirect_uri_type
		if (redirect_uri) {
			if (redirect_uri_type === 'activity') { // 区分活动页面和普通页面
				reLaunch({
					url: `?activityId=${redirect_uri}`,
					success() {
						delete getApp().globalData.temp_redirect_uri
						delete getApp().globalData.temp_redirect_uri_type
					}
				})
				return
			}
			uni.reLaunch({
				url: redirect_uri,
				success() {
					// 清除临时变量
					delete getApp().globalData.temp_redirect_uri
				}
			})
			return
		}
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}

	/**
	 * 参数转换
	 */
	function getQueryParams(urlParams) {
		let params = {};
		let pairs = urlParams.split('&');
		pairs.forEach(function(pair) {
			if (pair) {
				let [key, value] = pair.split('=');
				params[decodeURIComponent(key)] = decodeURIComponent(value);
			}
		});
		return params;
	}
</script>

<style lang="less" scoped>
</style>